from .. import NetworkBuilder
import pyecharts.options as opts
from pyecharts.charts import Bar
from pyecharts.globals import CurrentConfig

CurrentConfig.ONLINE_HOST = "https://cdn.jsdelivr.net/npm/echarts@latest/dist/"

__all__ = ['plot_nodes_attr']

def plot_nodes_attr(graph, feature, is_numeric=False):
    """
    绘制属性分布图。
    :param is_numeric: 该属性是否为数值型。若是，则以100为区间进行累计。
    :param graph: 图对象
    :param feature: 需绘制分布的属性
    :return:
    """

    # 统计属性分布
    distrib = NetworkBuilder.get_attr_distribution(graph, feature)
    x = list(distrib.keys())
    n = [distrib[i] for i in x]

    # 针对数值型属性进行优化
    if is_numeric:
        x0 = sorted(list(map(int, x)))
        max1 = x0[-1] // 100 + 1
        x1 = {str(i): 0 for i in range(max1)}
        for i in range(len(x0)):
            key = str(x0[i] // 100 + 1)
            x1[key] = x1.get(key, 0) + n[i]
        x = [int(i) for i in x1.keys()]
        n = list(x1.values())

    # 绘制分布图
    b = (
        Bar(init_opts=opts.InitOpts())
        .add_xaxis(xaxis_data=x)
        .add_yaxis(
            series_name="",
            y_axis=n,
            label_opts=opts.LabelOpts(is_show=False)
        )
        .set_global_opts(
            xaxis_opts=opts.AxisOpts(
                # type_="value" if is_numeric else "category",
                name=f"属性：{feature}"
            ),
            yaxis_opts=opts.AxisOpts(
                type_="value",
                name="频次",
            ),
            title_opts=opts.TitleOpts(title=f"{feature}属性分布图"),
            # datazoom_opts=opts.DataZoomOpts(type_="inside"),
        )
        .render(f"./output/attr_{feature}_distribution.html")
    )
